package com.lenovo.agent.ctrl;

import com.lenovo.agent.config.GitLabConfig;
import com.lenovo.agent.service.CodeReviewService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("/gitlab-webhook")
public class GitLabWebhookController {

    @Autowired
    private CodeReviewService codeReviewService;

    @Autowired
    private GitLabConfig gitLabConfig;

    @PostMapping("/code-review")
    public ResponseEntity<String> handleGitLabWebhook(
            @RequestHeader("X-Gitlab-Token") String token,
            @RequestBody String payload) {

        log.info("Received webhook with token: {}, payload: {}", token, payload);

        // 验证 Webhook Token
        if (!isValidToken(token)) {
            log.warn("Invalid token received: {}", token);
            return ResponseEntity.status(403).body("Invalid token");
        }

        // 处理 webhook 事件
        codeReviewService.processMergeRequest(payload);

        log.info("Webhook processed successfully");
        return ResponseEntity.ok("Webhook received");
    }

    private boolean isValidToken(String token) {
        // 从配置文件获取设置的 token 进行比对
        return gitLabConfig.getWebhookSecret().equals(token);
    }
}
